package com.effectivcrm.service;

import java.util.List;

import javax.xml.ws.ServiceMode;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import com.effectivcrm.domain.Lead;
import com.effectivcrm.repository.LeadRepository;
import com.mongodb.WriteResult
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import groovy.util.logging.Slf4j

@Slf4j

@Component
class LeadService {

	@Autowired
	LeadRepository repository;

	@Autowired
	MongoTemplate template;

	String ignoreFields  = [
		"serialVersionUID",
		"id",
		"version",
		"createdDate",
		"lastModifiedDate",
		"createdBy",
		"lastModifiedBy"
	];

	Lead create(Lead lead) {
		log.debug "Saving lead ${lead}"
		repository.save(lead);
		return lead;
	}


	Lead findOne(String id) {
		log.debug "Find lead with id : ${id}" 
		return repository.findOne(id);
	}


	int update(Lead lead) {

		String fieldName = null;

		Update u = new Update();

		ReflectUtil.getAccessibleFields(Lead.class).each{

			fieldName = f.getName();
			if(StringUtil.equalsOne(fieldName,ignoreFields) == -1){
				u.set(fieldName, BeanUtil.getPropertySilently(lead, fieldName));
			}
		}

		WriteResult r = template.updateFirst(query(where("id").is(lead.id) ), u, Lead.class);
		
		return r.getN();
	}


	//TODO - Currently only send all Leads which are active
	//ACTUAL - need to find the view (cached) and query based on those settings.
	List<Lead> findAll(String viewName) {
		return repository.findByDeleted(false);
	}


	int delete(String id) {
		Update u = new Update();
        u.set("deleted", true);
        WriteResult r = template.updateFirst(query(where("id").is(id) ), u, Lead.class);
		return r.getN();
	}


	List<Lead> findLastN(int noOfDocuments) {
		Query query = new Query();
		query.limit(noOfDocuments);
		query.with(new Sort(Sort.Direction.DESC, "createdDate"));

		return template.find(query, Lead.class);
	}

	//TODO - remove method when findAllIs implemented correctly.
	List<Lead> findByDeleted(boolean deleted) {
		return repository.findByDeleted(deleted);
	}

}
